# -*- coding: utf-8 -*-

from apps.common.base import BaseHandler
# from apps.log import Logger
from apps.plugins.email import EmailQueue
from apps.utils import Utils
import functools
import logging
off_line = 2
on_line = 1


def auth_checking(func):
    @functools.wraps(func)
    async def wrapper(self, *args, **kwargs):
        key = self.get_argument('key', default='')
        if key != '3^&$dsdf23':
            return self.render_json(-1, '请求密匙错误')
        await func(self, *args, **kwargs)
    return wrapper


class AlarmTypeHandler(BaseHandler):

    async def send_inform(self, almtype, device):
        user = self.get_user_by_id(device['user_id'])
        if user:
            almtype_text = '离线'
            if almtype == str(on_line):
                almtype_text = '上线'
            name = '设备({}){}通知 - 空明iot'.format(device['name'], almtype_text)
            body = '此邮件为系统在您设备状态发生变化时自动发送，如无异常情况，请忽略！'
            await EmailQueue.send([user['email']], name, body)
        else:
            logging.warning('获取用户信息失败' + str(device['user_id']))



    async def get(self, *args, **kwargs):
        sn = self.get_argument('sn', default='')
        almtype = self.get_argument('almtype', default='')

        if Utils.is_null(sn):
            return self.render_json(-1, '设备SN不能为空！')
        if Utils.is_null(almtype):
            return self.render_json(-1, 'almtype 不能为空')

        device = await self.device_model.get_device_by_sn(sn)
        if not device:
            return self.render_json(-1, '该设备不存在')

        # 处理设备状态
        if almtype == str(on_line):
            await self.device_model.set_device_status_by_uuid(
                device['uuid'], on_line, on_line, Utils.get_nowtime())
        elif almtype == str(off_line):
            status = on_line
            if device['status'] == off_line:
                status = off_line
            await self.device_model.set_device_status_by_uuid(
                device['uuid'], status, off_line)

        almsummary = '设备: {}'.format(device['name'])
        res = await self.alarm_model.add_alarm(Utils.get_uuid(), almtype,
                                                 almsummary, device['user_id'],
                                                 device['uuid'])
        if res:
            await self.send_inform(almtype, device)
            return self.render_json(0, 'ok')
        else:
            return self.render_json(-1, '失败')
